package com.woniu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.woniu.config.AlipayConfig;
import com.woniu.dao.*;
import com.woniu.pojo.*;
import com.woniu.service.PayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {

    Logger logger = LoggerFactory.getLogger("PayServiceImpl.class");

    @Autowired
    private CommunityOrderMapper communityOrderMapper;
    @Autowired
    private CommunityPayMapper communityPayMapper;
    @Autowired
    private ServiceOrderMapper serviceOrderMapper;
    @Autowired
    private UsedProductOrderMapper usedProductOrderMapper;
    @Autowired
    private CommunityActivityMapper communityActivityMapper;
    @Autowired
    private CommunityActivityUserMapper communityActivityUserMapper;

    public String payInfo(String no,String url,Integer type){
        //创建一个Client实例，其值在config中
        DefaultAlipayClient client = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key,
                "json", "utf8", AlipayConfig.alipay_public_key,AlipayConfig.sign_type);

        //封装订单信息
        Map map = new HashMap();
        String subject = null;
        double money = 0;

        //判断是哪一张订单
        switch (type){
            case 0:
                ServiceOrder serviceOrder = serviceOrderMapper.selectByNo(no);
                subject = "服务订单";
                money = serviceOrder.getOrderPrice();
                break;
            case 1:
                UsedProductOrder usedProductOrder = usedProductOrderMapper.selectByNo(no);
                subject = "商品订单";
                money = usedProductOrder.getOrderMoney();
                break;
            case 2:
                //社区活动订单，并封装到map中
                CommunityOrder communityOrder = communityOrderMapper.selectByNo(no);
                subject = "活动订单";
                money = communityOrder.getCoMoney();
                break;
        }
        map.put("subject",subject);      //订单名
        map.put("out_trade_no",no);                         //订单编号
        map.put("timeout_express","10m");                   //订单超时时间10分钟
        map.put("total_amount",String.valueOf(money)); //订单金额
        map.put("product_code","FAST_INSTANT_TRADE_PAY");   //产品码，必填

        //发送数据，先将数据转为request，最后通过client发出去，使用fastjson的toString方法
        //支付方式
//        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();// APP支付
//        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 网页支付
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();  //移动h5


        //异步同步通知跳转url
        request.setNotifyUrl(AlipayConfig.notify_url);
        //支付完成后跳转的地址，通过前端传递
        request.setReturnUrl(url);

        request.setBizContent(JSON.toJSONString(map));
        logger.info(JSON.toJSONString(map));
        String response = null;
        try {
            response = client.pageExecute(request).getBody();
            logger.info(response);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println(response);
        return response;
    }

    @Override
    public void delNotifyUrl(Map requestParams, Map trade, HttpServletResponse response) {
        Map params = new HashMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            System.out.println(name+" : "+valueStr);
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = false;
        try {
            verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, "RSA2");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if(verify_result){//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

                //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
                //商户订单号
                String out_trade_no = trade.get("out_trade_no").toString();
                //支付宝交易号
                String trade_no = trade.get("trade_no").toString();
                //交易状态
                String trade_status = trade.get("trade_status").toString();
                if(trade_status.equals("TRADE_FINISHED")){
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                    //如果有做过处理，不执行商户的业务程序
                    System.out.println("************************");
                    //注意：
                    //如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    //如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
                } else if (trade_status.equals("TRADE_SUCCESS")){
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                    //如果有做过处理，不执行商户的业务程序
                    if(params.get("out_biz_no")!=null){
                        System.out.println("这是退款");
                        System.out.println(params.get("return_url"));
                    }else{
                        System.out.println(params.get("return_url"));
                        System.out.println("这是支付");
                        if(params.get("subject").equals("活动订单")){
                            System.out.println("活动订单");
                            //更改活动订单状态
                            CommunityOrder communityOrder = communityOrderMapper.selectByNo(params.get("out_trade_no").toString());
                            communityOrder.setCoStatus(1);
                            communityOrderMapper.updateByPrimaryKeySelective(communityOrder);
                            //增加活动人数，新增活动用户信息
                            CommunityActivity communityActivity = communityActivityMapper.selectByPrimaryKey(communityOrder.getCoActivityId());
                            communityActivity.setCaPeopelCount(communityActivity.getCaPeopelCount()+1);
                            communityActivityMapper.updateByPrimaryKeySelective(communityActivity);
                            //更新用户报名状态
                            CommunityActivityUser communityActivityUser = communityActivityUserMapper.selectById(communityOrder.getCoActivityId(),communityOrder.getCoUserId());
                            communityActivityUser.setCauSignStatus(1);
                            communityActivityUserMapper.updateByPrimaryKeySelective(communityActivityUser);
                        }else if(params.get("subject").equals("服务订单")){
                            System.out.println("服务订单");
                            //更改订单状态
                            ServiceOrder serviceOrder = serviceOrderMapper.selectByNo(params.get("out_trade_no").toString());
                            serviceOrder.setStatus(0);
                            serviceOrderMapper.updateByPrimaryKeySelective(serviceOrder);
                        }else{
                            System.out.println("商品订单");
                            //更改商品订单状态
                            UsedProductOrder usedProductOrder = usedProductOrderMapper.selectByNo(params.get("out_trade_no").toString());
                            usedProductOrder.setOrderStatus(1);
                            usedProductOrderMapper.updateByPrimaryKeySelective(usedProductOrder);
                        }
                    }
                    //支付表
                    /**
                     * seller_email
                     * total_amount
                     * out_trade_no
                     * trade_no
                     * seller_id
                     * gmt_create 创建时间
                     * subject 商品名字
                     * buyer_id
                     * buyer_logon_id
                     */
                    //注意：
                    //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
                }

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
//            out.clear();
            try {
                response.getWriter().println("success");	//请不要修改或删除
            } catch (IOException e) {
                e.printStackTrace();
            }

            //////////////////////////////////////////////////////////////////////////////////////////
        }else{//验证失败
            try {
                response.getWriter().println("fail");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String refund(String no, Integer type) {
        //创建一个Client实例，其值在config中
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key,
                "json", "utf8", AlipayConfig.alipay_public_key,AlipayConfig.sign_type);

        //创建api对应的request类
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

        //定义一个map封装数据
        Map map = new HashMap();
        String money = null;

        //根据订单编号查询订单信息，并封装
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
       switch (type){
           case 0:
               ServiceOrder serviceOrder = serviceOrderMapper.selectByNo(no);
               money = String.valueOf(serviceOrder.getOrderPrice()-serviceOrder.getStopPrice());
               break;
           case 1:
               UsedProductOrder usedProductOrder = usedProductOrderMapper.selectByNo(no);
               money = String.valueOf(usedProductOrder.getOrderMoney());
               break;
           case 2:
               //CommunityPay communityPay = communityPayMapper.selectByNo(no);
               CommunityOrder communityOrder = communityOrderMapper.selectByNo(no);
               money = String.valueOf(communityOrder.getCoMoney());
//               map.put("out_trade_no",no);
//               map.put("trade_no",communityPay.getCpNum());
//               map.put("out_request_no","HZ01RF001");
//               map.put("refund_amount",0.03);
               break;
       }
        model.setRefundAmount(money);
        model.setOutTradeNo(no);
        model.setOutRequestNo("HZ01RF001");
        model.setRefundReason("121425不想要了");
//        request.setBizContent(JSON.toJSONString(map));
        request.setBizModel(model);
        logger.info(String.valueOf(model));
        String response = null;
        try {
//            response = client.pageExecute(request).getBody();
            response = client.execute(request).getBody();
            logger.info(response);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return response;
    }
}
